package com.yesep.learn.java8;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

public class Java8Junit {
	// 替代匿名内部类
	// 用lambda表达式实现Runnable
	@Test
	public void lambda_01() {
		// Java 8之前：
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Before Java8, too much code for too little to do");
			}
		}).start();

		// Java 8方式：
		new Thread(() -> System.out.println("In Java8, Lambda expression rocks !!")).start();
	}

	// 使用lambda表达式对列表进行迭代
	@Test
	public void lambda_02() {
		List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
		// Java 8之前：
		for (String feature : features) {
			System.out.println(feature);
		}

		// Java 8之后：
		features.forEach(n -> System.out.println(n));

		// 使用Java 8的方法引用更方便，方法引用由::双冒号操作符标示，
		// 看起来像C++的作用域解析运算符
		features.forEach(System.out::println);
	}

	// 使用lambda表达式和函数式接口Predicate
	@Test
	public void lambda_03() {

		List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");

		System.out.println("Languages which starts with J :");
		filter(languages, (str) -> str.startsWith("J"));

		System.out.println("Languages which ends with a ");
		filter(languages, (str) -> str.endsWith("a"));

		System.out.println("Print all languages :");
		filter(languages, (str) -> true);

		System.out.println("Print no language : ");
		filter(languages, (str) -> false);

		System.out.println("Print language whose length greater than 4:");
		filter(languages, (str) -> str.length() > 4);
	}

	public void filter(List<String> names, Predicate<String> condition) {
		for (String name : names) {
			if (condition.test(name)) {
				System.out.println(name + " ");
			}
		}
	}

	// 在lambda表达式中加入Predicate
	@Test
	public void lambda_04() {
		// 甚至可以用and()、or()和xor()逻辑函数来合并Predicate，
		// 例如要找到所有以J开始，长度为四个字母的名字，你可以合并两个Predicate并传入
		List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
		Predicate<String> startsWithJ = (n) -> n.startsWith("J");
		Predicate<String> fourLetterLong = (n) -> n.length() == 4;
		languages.stream().filter(startsWithJ.and(fourLetterLong)).forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));
	}

	// 使用lambda表达式的Map和Reduce示例
	// map的作用是将一个对象变换为另外一个,reduce实现的则是将所有值合并为一个。
	@Test
	public void lambda_05() {
		List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
		// 不使用lambda表达式为每个订单加上12%的税
		for (Integer cost : costBeforeTax) {
			double price = cost + .12 * cost;
			System.out.println(price);
		}
		// 使用lambda表达式
		costBeforeTax.stream().map((cost) -> cost + .12 * cost).forEach(System.out::println);

		double total = 0;
		for (Integer cost : costBeforeTax) {
			double price = cost + .12 * cost;
			total = total + price;
		}
		System.out.println("Total : " + total);

		// 新方法：
		double bill = costBeforeTax.stream().map((cost) -> cost + .12 * cost).reduce((sum, cost) -> sum + cost).get();
		System.out.println("Total : " + bill);
	}

	// 通过过滤创建一个String列表
	@Test
	public void lambda_06() {
		// 创建一个字符串列表，每个字符串长度大于4
		List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
		List<String> filtered = languages.stream().filter(x -> x.length() > 4).collect(Collectors.toList());
		System.out.printf("Original List : %s, filtered list : %s %n", languages, filtered);
	}

	// 对列表的每个元素应用函数
	@Test
	public void lambda_07() {
		// 将字符串换成大写并用逗号链接起来
		List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.", "Canada");
		String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
		System.out.println(G7Countries);
	}

	// 复制不同的值，创建一个子列表
	@Test
	public void lambda_08() {
		// 用所有不同的数字创建一个正方形列表
		List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
		List<Integer> distinct = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
		System.out.printf("Original List : %s,  Square Without duplicates : %s %n", numbers, distinct);
	}

	// 计算集合元素的最大值、最小值、总和以及平均值
	@Test
	public void lambda_09() {
		// 获取数字的个数、最小值、最大值、总和以及平均值
		List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
		IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
		System.out.println("Highest prime number in List : " + stats.getMax());
		System.out.println("Lowest prime number in List : " + stats.getMin());
		System.out.println("Sum of all prime numbers : " + stats.getSum());
		System.out.println("Average of all prime numbers : " + stats.getAverage());
	}

	// 其它觉使用方式
	@Test
	public void lambda_10() {

		// 判断是否偶数
		IntPredicate evenNumbers = (int i) -> i % 2 == 0;
		assertTrue(evenNumbers.test(1000));
		// 判断是否奇数
		Predicate<Integer> oddNumbers = (Integer i) -> i % 2 == 1;
		assertFalse(oddNumbers.test(1000));
		// 整形参数加1
		Function<Integer, Integer> add1 = x -> x + 1;
		assertThat(add1.apply(1), equalTo(2));
		// 字符数据连接
		Function<String, String> concat = x -> x + 1;
		assertThat("字符数据连接", concat.apply("0 + 1 = "), equalTo("0 + 1 = 1"));
		// 两数之和
		// BinaryOperator<Integer> sum = (x, y) -> x + y;
		BinaryOperator<Integer> sum = (x, y) -> {// 多行代码
			System.out.println("x : " + x);
			System.out.println("y : " + y);
			System.out.println("x + y : " + (x + y));
			return x + y;
		};
		assertThat("两数之和", sum.apply(1, 2), equalTo(3));

		// 复杂多层调用
		Function<Integer, UnaryOperator<Integer>> sum2 = x -> y -> x + y;
		assertThat("复杂多层调用", sum2.apply(5).apply(5), equalTo(10));

		BinaryOperator<Function<Integer, Integer>> compose = (a, b) -> x -> b.apply(a.apply(x));
		Function<Integer, Integer> compose_res = compose.apply(x -> x + 2, y -> y + 2);
		assertThat("复杂多层调用", compose_res.apply(5), equalTo(9));
	}
}
